package duyd.mvc.training.controller;

import static org.quartz.TriggerBuilder.newTrigger;
import static org.quartz.TriggerKey.triggerKey;

import java.util.List;

import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import duyd.mvc.training.domain.Contact;
import duyd.mvc.training.service.ContactService;

@Controller
@RequestMapping("/contact")
public class ContactController {
	final Logger logger = LoggerFactory.getLogger(ContactController.class);

	@Autowired
	private ContactService contactService;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model viewModel) {
		logger.info("Listing contacts: ");
		List<Contact> contacts = contactService.findAll();
		viewModel.addAttribute("contacts", contacts);
		logger.info("No. of contacts: " + contacts.size());

		updateTestJob();

		return "contact/list";
	}

	public void updateTestJob() {
		SchedulerFactory sf = new StdSchedulerFactory();
		try {
			Scheduler scheduler = sf.getScheduler();
			// retrieve the trigger
			Trigger oldTrigger = scheduler.getTrigger(triggerKey("testTrigger",
					"testGroup"));

			Trigger newTrigger = newTrigger()
					.withIdentity("testTrigger", "testGroup")
					.startNow()
					.withSchedule(
							SimpleScheduleBuilder.repeatSecondlyForTotalCount(
									2, 5).repeatForever()).build();

			scheduler.rescheduleJob(oldTrigger.getKey(), newTrigger);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
